<template>
    <div class="content">
        <div class="login" >
            <div><label for="">用户名：</label><input @keydown.enter="login" v-model="user" type="text"></div>
            <div><label for="">密码：</label><input @keydown.enter="login" v-model="password" type="password"></div>
            <div class="button">
                <input @click="login" type="button" name="" id="" value="登录">
                <input @click="$router.push('/register')" type="button" name="" id="" value="注册">
            </div>
        </div>
    </div>
</template>

<script>
import { JSEncrypt } from 'jsencrypt'
import private_key from '@/private_key.js'
export default {
    name:'login',
    data(){
        return {
            user:'',
            password:''
        }
    },
    methods:{
        login(){
            // let pwd_hash = this.$data_encryption.Encrypt(this.password)  // 对密码进行hash
            // console.log(pwd_hash);
            // let pwd = this.$data_encryption.Decrypt(pwd_hash)
            // console.log(pwd);
            this.$http({
                method:'post',
                url:'/ajax/api/login',
                data:{
                    user:this.user,
                    password:this.password
                }
            }).then(data=>{
                console.log(data.data);
                if(data.data=="no"){
                    this.$toast("用户名或密码错误，登录失败")
                }else{
                    // 把JSON对象转换成字符串,并存储在本地
                    let logininfo = data.data
                    // 获取当前时间戳，并设置登录有效期(1天)
                    let new_time = Date.now() + 24*60*60*1000
                    logininfo.expire = new_time
                    let logininfo_str=JSON.stringify(logininfo)  
                    localStorage.setItem('logininfo',logininfo_str)
                    // 重新设置post请求的token
                    this.$http.defaults.headers.common['token'] = logininfo.token;
                    this.$http.defaults.headers.common['username'] = logininfo.user;
                    this.$store.state.global_var.logininfo = logininfo
                    this.$toast("登录成功")
                    this.$router.push('/')
                    // 这里把获取本地存储的方法也写出来，备用
                    // let logininfo=JSON.parse(localStorage.getItem('logininfo'))
                }
            })
        }
    },
    mounted(){
    },
}
</script>

<style lang='scss' scoped>
    .login{
        margin: 10px 50px;
        display: flex;
        flex: 1;
        // background-color: pink;
        flex-direction: column;
        justify-content: center;
        // align-items: center;
        width: 280px;
        div{
            margin: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .button{
            margin:5px 10px;
        }
    }
</style>